/* 
  控制每次最多只能发送maxCount个请求获取次数，超过的必须等待前面的完成才可以继续发送
*/
function handleRequest(url) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(url);
      console.log('complete ', url);
    }, 1000);
  });
}
function request(urls, maxCount) {
  return new Promise((resolve, reject) => {
    urls = urls || [];
    maxCount = maxCount || 1;
    const size = urls.length;
    const result = Array(size).fill(false);
    let count = 0; // 记录目前有几个请求在处理
    const next = () => {
      const index = count++;
      const url = urls[index];
      if (index >= size) {
        resolve(result);
        return;
      }
      handleRequest(url)
        .then((data) => {
          result[index] = data;
          if (index < size) {
            next();
          }
        })
        .catch((err) => {
          result[index] = err;
          if (count < size) {
            next();
          }
        });
    };

    while (count < maxCount) {
      next();
    }
  });
}

const urls = [1, 2, 3, 4, 5, 6];
request(urls, 2);
